package cn.bjit.controller;

import cn.bjit.enums.BizCodeEnum;
import cn.bjit.enums.SendCodeEnum;
import cn.bjit.service.NotifyService;
import cn.bjit.util.CommonUtil;
import cn.bjit.util.JsonData;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Api(tags = "通知模板")
@RestController
@RequestMapping("/api/user/v1")
@Slf4j
public class NotifyController {
    @Autowired
    private Producer captchaProducer;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private NotifyService notifyService;
      //图形验证码有效时间10分钟
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;
    /**
     * 获取图形验证码
     * @param request
     * @param response
     */
    @ApiOperation("获取图形验证码")
    @GetMapping("/captch")
    public void Captch(HttpServletRequest request, HttpServletResponse response) {

        String captchaText = captchaProducer.createText();
        log.info("图形验证码{}", captchaText);

        //存储到redis中
        redisTemplate.opsForValue().set(this.getCaptchKey(request),captchaText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        BufferedImage bufferImage = captchaProducer.createImage(captchaText);
        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            ImageIO.write(bufferImage, "jpg", servletOutputStream);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (IOException e) {
            log.info("图形验证码异常{}", e);
        }
    }

    /**
     * 获取存储到redis缓存中的key
     * @param request
     * @return
     */
    public String getCaptchKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent=request.getHeader("User-Agent");
        String key="user-service:captch:"+CommonUtil.MD5(ipAddr+userAgent);
        log.info("ip地址={}",ipAddr);
        log.info("userAgent={}",userAgent);
        log.info("key={}",key);
        return key;
    }

    /**
     *
     * @param to 发送给谁
     * @param captch  页面传递过来的图形验证码
     * @param request
     * @return
     */
    @ApiOperation("发送邮箱验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam(value = "to",required = true) @ApiParam(value = "邮箱接收者",required = true) String to, @ApiParam(value = "图形验证码",required = true) String captch, HttpServletRequest request){
        String captchKey = this.getCaptchKey(request); //获取存储在redis中的key
        log.info("存储在redis中的key={}",captchKey);
        String captchCaptch = redisTemplate.opsForValue().get(captchKey);//根据redis的key获取value也就是验证码

        if(captch!=null&&captchCaptch!=null&&captch.equalsIgnoreCase(captchCaptch)){  //成功
            redisTemplate.delete(captchKey);
             //发送邮箱验证码
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER,to);
            return jsonData;
        }else{//失败
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR); //验证码错误
        }
    }
}
